package com.olc.railing.ui;

import android.Manifest;
import android.app.AlarmManager;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.google.gson.Gson;
import com.olc.railing.base.BaseActivity;
import com.olc.railing.R;
import com.olc.railing.base.BaseApplication;
import com.olc.railing.busniess.BLEServer;
import com.olc.railing.busniess.DataBusiness;
import com.olc.railing.busniess.LampControler;
import com.olc.railing.busniess.MyThreadPoolExecutor;
import com.olc.railing.camera.CameraActivity;

import com.olc.railing.camera.VedioActivity;
import com.olc.railing.constant.Constants;
import com.olc.railing.model.ConfigInfo;
import com.olc.railing.model.EventInfo;
import com.olc.railing.model.PayStatus;
import com.olc.railing.model.UserInfo;
import com.olc.railing.orm.UserInfoDao;
import com.olc.railing.services.DelRedFileServices;

import com.olc.railing.services.UploadTradeInfoServices;
import com.olc.railing.utils.CommUtils;
import com.olc.railing.utils.LogcatHelper;
import com.olc.railing.utils.MyLog;
import com.olc.railing.utils.SharedUtils;
import com.olc.railing.utils.TimeUtils;


import org.apache.log4j.chainsaw.Main;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.schedulers.Schedulers;
import pr.platerecognization.OcrBusiness;

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class MainActivity extends BaseActivity {

    private static final String TAG = "MainActivity";
    @BindView(R.id.textview)
    TextView textview;
    @BindView(R.id.vehilce_no_tv)
    TextView vehilce_no_tv;
    @BindView(R.id.vedio_path_tv)
    TextView vedio_path_tv;

    private Timer timer;
    private int count;
    private MyHandler handler = new MyHandler(this);
    private boolean mBound = false;

    private static class MyHandler extends Handler {
        private WeakReference<MainActivity> mainActivityWeakReference;

        private MyHandler(MainActivity mainActivity) {
            mainActivityWeakReference = new WeakReference<>(mainActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {

                case 108:
                    if (mBluetoothAdapter.isEnabled()) {
                        mainActivityWeakReference.get().initBle();
                    } else {
                        sendEmptyMessageDelayed(108, 5000);
                    }
                    break;
                case 109:
                    mainActivityWeakReference.get().startService(new Intent(BaseApplication.getApplication(), DelRedFileServices.class));
                    break;

                case 2:
                    mainActivityWeakReference.get().configIpToScreen();
                    break;

                case DataBusiness.QUERY_CONFIG_FAIL:
                    mainActivityWeakReference.get().count++;
                    if (mainActivityWeakReference.get().count < 5) {
                        sendEmptyMessageDelayed(4, 3000);
                    }
                    break;

                case DataBusiness.QUERY_CONFIG_SUCCESS:
                    ConfigInfo configInfo = (ConfigInfo) msg.obj;
                    MyLog.d(MyLog.TAG, "configInfo: " + configInfo.toString());
                    mainActivityWeakReference.get().initEtcPay(configInfo);
                    sendEmptyMessageDelayed(5, 2000);
                    break;

                case 5:
                    DataBusiness.getInstance(BaseApplication.getApplication()).pushHeart();
                    sendEmptyMessageDelayed(5, 2 * 60 * 1000);
                    break;


            }
        }

    }


    @Override
    public int getLayoutResId() {
        return R.layout.activity_main;
    }

    private static BluetoothManager mBluetoothManager;
    private static BluetoothAdapter mBluetoothAdapter;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void init() {
        MyLog.d(MyLog.TAG, "versionName: " + CommUtils.getVerName(this));
        netChecker();
        LampControler.initGpio();
        initLamp();
        if (isPermission()) {
            vehOcr();
        } else {
            //请求权限
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA,
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.ACCESS_FINE_LOCATION}, 200);
        }
        textview.setText(getVerName(this));
        vedio_path_tv.setText("视频路径： " + BaseApplication.SD_PATH);
        // 蓝牙初始化
        initBt();
        //启动删除数据服务
        handler.sendEmptyMessageDelayed(109, 10 * 1000);
        //播放开始语音
        playMedia(R.raw.welcome);
        EventBus.getDefault().register(this);
        handler.sendEmptyMessageDelayed(2, 4000);

        getConnectWifiSsid();
        createTimer();
        //获取配置信息
        DataBusiness.getInstance(BaseApplication.getApplication()).queryConfig(handler);
        openService();


    }

    private void createTimer() {
        if(timer==null){
            timer = new Timer(true);
        }
        timer.schedule(new BTTask(), 2000, 30 * 1000); //延时1000ms后执行，1000ms执行一次
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(timer!=null){
                    timer.cancel();
                    timer = null;
                }

            }
        }, 10 * 60 * 1000);
    }


    private void initBt() {
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            // 设备没有蓝牙
            return;
        } else {
            mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
            mBluetoothAdapter = mBluetoothManager.getAdapter();
            String deviceNo = CommUtils.getDeviceSN();
            mBluetoothAdapter.setName("dcg_"+deviceNo.substring(deviceNo.length()-6));

            if (mBluetoothAdapter.isEnabled()) {
                initBle();
            } else {
                mBluetoothAdapter.enable();
                handler.sendEmptyMessageDelayed(108, 2000);
            }
        }
    }

    private void initBle() {
        MyLog.d(MyLog.TAG, "ble--initBle: " );
        // 检查蓝牙开关
        BLEServer.getInstance().initBlueTooth(MainActivity.this, mBluetoothAdapter, mBluetoothManager, new BLEServer.BLEServerCallback() {
            @Override
            public void onAdvertiseEnable(boolean isSuccess) {

            }

            @Override
            public void onConnectStateChange(BluetoothDevice device, int status, int newStatus) {
                //logTv(String.format(status == 0 ? (newState == 2 ? "与[%s]连接成功" : "与[%s]连接断开") : ("与[%s]连接出错,错误码:" + status), device));
                     /*  if(status == 0){
                           if(newStatus == 2 ){
                               playMedia(new int[]{R.raw.ble_connect_success},0);
                           }else{
                               playMedia(new int[]{R.raw.ble_connect_close},0);
                           }
                       }else{
                           playMedia(new int[]{R.raw.ble_connect_fail},0);
                       }*/
            }

            @Override
            public void onPrintLog(String log) {

            }

            @Override
            public void onPrintMsg(String msg) {

            }

            @Override
            public void configWifi(boolean reslt) {
                if (reslt) {
                    playMedia(R.raw.config_wifi_success);
                } else {
                    playMedia(R.raw.config_wifi_fail);
                }
            }

            @Override
            public void configOilNo(boolean reslt) {
                if (reslt) {
                    playMedia(R.raw.oil_no_set_success);
                } else {
                    playMedia(R.raw.oil_no_set_fail);
                }

            }

            @Override
            public void configIpAdress(boolean reslt) {
                if (reslt) {
                    playMedia(R.raw.add_ip_success);
                } else {
                    playMedia(R.raw.add_ip_fail);
                }
            }

            @Override
            public String onReadRequest(UUID uuid) {
                return null;
            }
        });


    }

    private class BTTask extends TimerTask {

        @Override
        public void run() {
            BLEServer.getInstance().restartAdvertising();
        }
    }


    @OnClick({R.id.start_btn, R.id.play_btn, R.id.consume_btn, R.id.ocr_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.start_btn:
                // openBuguangLamp();
                // BaseApplication.cameraId = 1;
                // isRecord  = true;
                startService(new Intent(MainActivity.this, DelRedFileServices.class)/*.
                        putExtra("mPlateNo","陕A23334")*/);
                break;
            case R.id.play_btn:
                //closeBuguangLamp();
                // PlayMediaBusiness.getInstance().play(this,R.raw.start_oil);
           /*     flag = !flag;
                ToastUtils.showToast(this,"flag "+flag);
                JwsBusiness.getInstance(this).jwsobject.jwsSetExtrnalGpioValue(1,flag);// 0 控制拍照*/


                // MyLog.d(TAG,"imagePath : "+imagePath);///storage/emulated/0/DCIM/Camera/IMG_20210207_230620.jpg
            /*    Bitmap retBitmap = OcrBusiness.getInstance(this).decodeImage("/storage/emulated/0/DCIM/Camera/IMG_20210207_231227.jpg");
              //  MyLog.d(TAG,"retBitmap : "+retBitmap);
                PlateInfo plateInfo = OcrBusiness.getInstance(this).SimpleRecog(retBitmap,3);
                textview.setText(plateInfo.getPlateName());*/
                break;
            case R.id.consume_btn:
                //  etcPay();
                break;

            case R.id.ocr_btn:
                break;
        }

    }

    private void vehOcr() {
        MyThreadPoolExecutor.getMyThreadPoolInstance().getMyThreadPoolExecutor().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    OcrBusiness.getInstance(MainActivity.this).initRecognizer();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //开始识别车牌，----打开相机---- 关闭相机
                 //   打开录像-----关闭录像



   /* @Override
    public void startOcr() {
        super.startOcr();
        handler.sendEmptyMessageDelayed(1, 1000);

    }
*/
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MyLog.d(MyLog.TAG, "权限申请 requestCode " + requestCode);
        switch (requestCode) {
            case 200:
                MyLog.d(MyLog.TAG, "权限申请 permissions.length  " + permissions.length);
                if (permissions != null && permissions.length > 0) {
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        //   bindService(new Intent(this,GpioService.class),gpioConnection,BIND_AUTO_CREATE);
                        vehOcr();
                        playMedia(R.raw.welcome);
                    }
                }
                break;

        }

    }

    public static String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().
                    getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageInfo(EventInfo eventInfo) {
        if(eventInfo!=null){
            MyLog.d(MyLog.TAG,"onMessageInfo eventInfo  "+eventInfo.toString());
            int code = eventInfo.getCode();
            if(Constants.START_UPLOAD_ORDER_TO_SERVER == code){
                uploadTradeInfoServices.uploadTradeInfo(eventInfo.getContent());
            }else if(Constants.OCR_VHEPLATE_NO == code){
                plateNo = eventInfo.getContent();
                vehilce_no_tv.setText(plateNo);
                saveUserInfo();
                startRecord();
            }
        }else{
            MyLog.d(MyLog.TAG,"eventInfo is null ");
        }
    }
    public void startRecord() {
        MyLog.d(MyLog.TAG,"开启录像");
        startActivity(new Intent(this, VedioActivity.class).
                putExtra("mPlateNo",plateNo));
    }

    /**
     * 记录挡车杆信息
     */
    private void saveUserInfo() {
        MyLog.d(MyLog.TAG, "saveUserInfo");
        UserInfo userInfo = new UserInfo();
        userInfo.setEntranceTime(TimeUtils.getTime("yyyy/MM/dd HH:mm", System.currentTimeMillis() + ""));
        userInfo.setEtcPayStatus(PayStatus.NO_PAY.code + "");
        userInfo.setOcrVehPlate(plateNo);
        userInfo.setOilGunNo(SharedUtils.getOilGunNo(this));
        String serialNo = CommUtils.getUUId();
        SharedUtils.setSerialNo(this, serialNo);
        userInfo.setSerialNo(serialNo);
        new UserInfoDao(BaseApplication.getApplication()).insert(userInfo);
        if (socketClient != null) {
            socketClient.sendStrData(new Gson().toJson(userInfo));
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if(timer!=null){
            timer.cancel();
            timer = null;
        }
    }

    private String getConnectWifiSsid() {


        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);

        WifiInfo wifiInfo = wifiManager.getConnectionInfo();

        MyLog.d(MyLog.TAG, "wifiInfo------" + wifiInfo.toString());

        MyLog.d(MyLog.TAG, "SSID------" + wifiInfo.getSSID());

        return wifiInfo.getSSID();

    }


    //网络监测
    private void netChecker() {
        long netFrequence = 20;
        Observable.interval(15, netFrequence, TimeUnit.SECONDS)
                .observeOn(Schedulers.newThread())
                .flatMap(aLong ->  {
                    boolean isNetOk = CommUtils.isNetworkConnected(MainActivity.this);
                    Log.e(TAG, "网络判断1:" + isNetOk + " " + Thread.currentThread().getName());
                    return Observable.just(isNetOk);
                })
                .observeOn(AndroidSchedulers.mainThread())
                .flatMap(aBoolean ->  {
                    return Observable.create(new ObservableOnSubscribe<Integer>() {
                        @Override
                        public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Exception {
                            Log.e(TAG, "网络判断2:" + aBoolean + " " + Thread.currentThread().getName());
                            if (aBoolean) {
                                emitter.onNext(0);
                            }
                            emitter.onComplete();
                        }
                    });
                })
                .observeOn(Schedulers.io())
                .subscribe(integer ->  {
                    Log.e(TAG, "网络判断3:" + integer + " " + Thread.currentThread().getName());
                    if (integer == 0) { // 有网 更新时间
                        updateTimeByNet();
                    }

                });
    }

    /**
     * 更新时间显示
     */
    public void updateTimeByNet() {

        try {
            URL url = new URL("http://www.baidu.com");//取得资源对象

            URLConnection uc = url.openConnection();//生成连接对象

            uc.connect(); //发出连接

            final long ld = uc.getDate(); //取得网站日期时间

            try {
                long when = new Date(ld).getTime();
                Log.e("MainActivity", "servertime==" + when );
                ((AlarmManager) getSystemService(Context.ALARM_SERVICE)).setTime(when);
                Intent timeChanged = new Intent(Intent.ACTION_TIME_CHANGED);
                sendBroadcast(timeChanged);
                if(isFristStart){//保证日志时间正确
                    isFristStart = false;
                    LogcatHelper.getInstance(this).start();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean isFristStart = true;

    @Override
    public void startOcr() {
        super.startOcr();
        String ipAdress =  SharedUtils.getIpAdress(this);
        if(TextUtils.isEmpty(ipAdress)){
            playMedia(R.raw.no_add_ip);
            return;
        }
        playMedia(R.raw.kaishisibiechepai);
        startActivity(new Intent(MainActivity.this, CameraActivity.class));
    }

    private void openService() {
        Intent intent = new Intent(this, UploadTradeInfoServices.class);
        bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }

    private UploadTradeInfoServices uploadTradeInfoServices;
    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className,
                                       IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            UploadTradeInfoServices.UploadBinder binder = (UploadTradeInfoServices.UploadBinder) service;
            uploadTradeInfoServices = binder.getService();
            mBound = true;
            MyLog.d(MyLog.TAG,"onServiceConnected "+uploadTradeInfoServices);
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };
}